package com.quwan.app.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.quwan.app.service.VipService;
import com.quwan.app.vo.VipInfoDTO;
import com.quwan.app.vo.pay.PrePayParams;
import com.quwan.app.vo.pay.PrePayment;
import com.quwan.common.BaseController;
import com.quwan.common.Check;
import com.quwan.common.enums.PaymentEnum;
import com.quwan.common.exception.ExpCode;
import com.quwan.common.result.ApiResult;
import com.quwan.component.ComponentFactory;
import com.quwan.entity.TVipRights;
import com.quwan.entity.TVipRule;
import com.quwan.mapper.TVipRuleMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author quan
 * @date 2022-04-25 17:56
 */
@Api(tags = "vip")
@RestController
@RequestMapping("app/vip")
@RequiredArgsConstructor
public class VipController extends BaseController {
    private final VipService vipService;
    private final TVipRuleMapper vipRuleMapper;

    private final ComponentFactory componentFactory;

    @ApiOperation("vip展示页数据")
    @GetMapping("data")
    public ApiResult<VipInfoDTO> vipData() {
        List<TVipRights> rights = vipService.getVipRightsList();
        List<TVipRule> rules = vipService.getVipRuleList();
        return ApiResult.success(new VipInfoDTO().setRights(rights).setVips(rules));
    }

    @ApiOperation("vip开通")
    @PostMapping("buyIt")
    public ApiResult<PrePayment> rechargeVip(HttpServletRequest request,
                                             @ApiParam("vip rule id") @RequestParam String vipId,
                                             @ApiParam("支付类型 0系统支付  1：微信 2支付宝") @RequestParam String payMethod) {
        final String mId = getId(request);

        TVipRule rule = vipRuleMapper.selectById(vipId);
        Check.notNull(rule, ExpCode.DATA_ILLEGAL);

        BigDecimal price = rule.getPrice();
        String rechargeNum = IdWorker.getIdStr();
        PaymentEnum payment = PaymentEnum.getByType(payMethod);
        Check.notNull(payment, ExpCode.PAY_NOT_SUPPORT);

        PrePayment prePayment =
                vipService.saveVipPrepayInfo(
                        new PrePayParams(price.toString(), rechargeNum, "rechargeVip", payment.getVip(), mId),
                        mId,
                        payMethod,
                        vipId,
                        componentFactory.getPayInstance(payment));

        return ApiResult.success(prePayment);

    }


}
